package com.jthinker.blog.web.controller.admin.post;

import com.jthinker.blog.bean.entity.Category;
import com.jthinker.blog.service.CategoryService;
import com.jthinker.blog.web.controller.admin.common.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * User: Gang Chen
 * Date: 2015/7/5 10:47
 */
@Controller
@RequestMapping("/categoryMgr")
public class CategoryMgrController extends BaseController
{
    @Autowired
    private CategoryService categoryService;

    @RequestMapping("/view")
    public String view()
    {
        return null;
    }

    @RequestMapping("/listView")
    public String listView()
    {
        return "category/categoryList";
    }

    @RequestMapping("/getListData")
    @ResponseBody
    public Map<String, Object> getListData(HttpServletRequest request)
    {
        return getListDataByEntity(request, categoryService, Category.class);
    }

    @RequestMapping("/getSelectData")
    @ResponseBody
    public List<Map<String, Object>> getSelectData(HttpServletRequest request)
    {
        return getSelectData(request, categoryService, "id", "name", Category.class);
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Map<String, Object> saveOrUpdate(@Valid Category category, BindingResult result)
    {
        if (result.hasErrors())
        {
            return generateErrorMessage(result);
        }

        if (!categoryService.isUnique(category, "slug"))
        {
            return getErrorMessage("别名" + category.getSlug() + "已存在!");
        }

        categoryService.merge(category);

        return getSuccessMessage("保存成功!");
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Map<String, Object> delete(Long id)
    {
        if (id == null || id == 1l)
        {
            return getErrorMessage("请选择行!");
        }
        categoryService.delete(id);
        return getSuccessMessage("删除成功!");
    }

}
